#!/usr/bin/python
#-*- coding: utf-8 -*-
# @Time    : 2019/2/20 6:44 PM
# @Author  : way
# @Email   : wuaoyi@gmail.com
# @File    : exchange2.7.py
# @Software: PyCharm
import requests,re
import time
import json
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
import os,io
import random

import sys
reload(sys)
sys.setdefaultencoding('utf8')

class Exchange:
    # 毫秒级的时间戳
    timestamp = int(round(time.time() * 1000))
    # 当前日期
    ctime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    #日志文件的路径
    filePath = ''+ctime + ".txt"
    #上海交易所的股票代码
    shStock = ['600715', '600637', '600373', '603533', '601360', '600640', ]
    shTile = {'600715':'文投控股', '600637':'东方明珠', '600373':'中文传媒', '603533': '掌阅', '601360': '三六零', '600640': '号百控股'}
    #深圳交易所的股票代码
    szStock = ['002739', '002624', '300251', '002292', '002699', '300027', '300133', '002174', '000917', '300418', '002555', '300144', '002354', '300315', '300364', '300043', '300571', '002602', '002558', '002143', '300413']
    #上海交易所返回的列表
    shData = {}
    #深圳交易所返回的列表
    szData= {}
    #s上海交易所的静态网址
    shLink = 'http://static.sse.com.cn'
    #深圳交易所pdf静态链接
    szLink = 'http://www.szse.cn/disclosure/listed/bulletinDetail/index.html?'
    #爬取深圳交易所的接口地址
    szUrl = 'http://www.szse.cn/api/disc/announcement/annList?random=%s'
    #爬取上海交易所得接口地址
    shUrl = 'http://www.sse.com.cn/js/common/stocks/new/%s.js?_=' + str(timestamp)
    #抓取深圳交易所的数据
    def shenzhen(self):
        #抓取数据的参数
        payload2 = {'seDate': [self.ctime, self.ctime], 'stock': self.szStock, 'channelCode': ["listedNotice_disc"],
                    'pageSize': 100, 'pageNum': 1}

        #抓取数据URL的随机数
        num = '0.%s%s' % (self.timestamp, random.randint(1000, 9999))
        url = self.szUrl % (num)

        #抓取数据
        data = requests.post(url, data=json.dumps(payload2), headers={'Content-Type': 'application/json'})
        szRes = data.json()

        #抓取得数据不为空得时候，将数组写入字典并返回结果
        if len(szRes['data']) > 0:
            for res in szRes['data']:
                #key = res['secName'][0]
                key = res['title']
                content ='<a href="' + self.szLink + res['id'] + '">' + res['title'] + '</a>'
                self.szData.setdefault(key, [])
                self.szData[key].append(content)
        return  self.szData


    #抓取上海交易所的内容
    def shanghai(self):
        for i in self.shStock:
            url = self.shUrl % (i)
            shRes = requests.get(url).text

            result= re.findall(r'bulletin_date:"' + self.ctime + '",bulletin_year:"(.*?)",bulletin_large_type:"(.*?)",bulletin_small_type:"(.*?)",bulletin_title:"(.*?)",(.*?)",', shRes)
            if len(result) > 0:
                for res in result:
                    #key = self.shTile[i]
                    key = res[3]
                    content = '<a href="' + self.shLink + i[4].replace('bulletin_file_url:"', '') + '">' + res[3] + '</a>'
                    self.shData.setdefault(key, [])
                    self.shData[key].append(content)
                return self.shData

    #发送邮件公告
    def doData(self, data, msgStr):
        mailObj = SendEmail()

        if data is not None and len(data) > 0:
            for i in data:
                content = self.delRepeat(msgStr, data[i])
                #去掉重复后的邮件内容不为空，发送邮件
                if len(content) > 0:
                    #获取发送邮件的结果
                    smRes = mailObj.sendMail(i, content)

                    content = content.replace('<br/>', "\n");
                    if smRes:
                        with open(self.filePath, mode='a+') as f:
                            f.write(content+"\n")
                        f.close();

    #去掉已经发布过的公告
    def delRepeat(self, oldMsg, newList):
        tmpData = []
        for value in newList:
            # dr = re.compile(r'<[^>]+>', re.S)
            # newTmp = dr.sub('', value)
            if oldMsg.find(value) < 0:
                tmpData.append(value)
        return "<br/>".join(tmpData)





class SendEmail:
    # 发件人地址，通过控制台创建的发件人地址
    username = 'support@ucoin.pw'
    # 发件人密码，通过控制台创建的发件人密码
    password = 'LIxing123456'
    # 自定义的回复地址
    replyto = ''
    # 收件人地址或是地址列表，支持多个收件人，最多30个
    rcptto = ['xc_beyond@163.com', 'v@3wyu.com', 'asi@3wyu.com']
    #rcptto = ['xc_beyond@163.com']
    #发件人标题
    title = "今日快讯"
    #发件人
    poster = '三文娱'
    # 发送邮件
    def sendMail(self, title, content):
        self.title = title
        # 构建alternative结构
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(self.title.decode('utf-8')).encode()
        msg['From'] = '%s <%s>' % (Header(self.poster.decode('utf-8')).encode(), self.username)
        msg['To'] = ', '.join(self.rcptto)
        msg['Reply-to'] = self.replyto
        msg['Message-id'] = email.utils.make_msgid()
        msg['Date'] = email.utils.formatdate()
        # 构建alternative的text/plain部分
        textplain = MIMEText('szList', _subtype='plain', _charset='UTF-8')
        msg.attach(textplain)
        # 构建alternative的text/html部分
        texthtml = MIMEText(content, _subtype='html', _charset='UTF-8')
        msg.attach(texthtml)
        # 发送email
        try:
            client = smtplib.SMTP()
            # SMTP普通端口为25或80
            client.connect('smtpdm.aliyun.com', 25)
            # 开启DEBUG模式
            client.set_debuglevel(0)
            client.login(self.username, self.password)
            # 发件人和认证地址必须一致
            # 备注：若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
            #      使用SMTP.mail/SMTP.rcpt/SMTP.data方法
            client.sendmail(self.username, self.rcptto, msg.as_string())
            client.quit()
            print 'email发送成功！'
            return True
        except smtplib.SMTPConnectError , e:
            print 'email发送失败，连接失败:', e.smtp_code, e.smtp_error
        except smtplib.SMTPAuthenticationError , e:
            print 'email发送失败，认证错误:', e.smtp_code, e.smtp_error
        except smtplib.SMTPSenderRefused , e:
            print 'email发送失败，发件人被拒绝:', e.smtp_code, e.smtp_error
        except smtplib.SMTPRecipientsRefused , e:
            print 'email发送失败，收件人被拒绝:', e.smtp_code, e.smtp_error
        except smtplib.SMTPDataError , e:
            print 'email发送失败，数据接收拒绝:', e.smtp_code, e.smtp_error
        except smtplib.SMTPException , e:
            print 'email发送失败, ', e.message
        except Exception , e:
            print 'email发送异常, ', str(e)
            return False

if __name__ == "__main__":
    exObj = Exchange()
    shData = exObj.shanghai()
    szData = exObj.shenzhen()

    # python 读取文件必须是 mode = 'r'
    with open(exObj.filePath, mode='a+') as f:
        f.seek(0)
        msgStr = f.read()
    f.close();

    #发送邮件
    exObj.doData(shData, msgStr)
    exObj.doData(szData, msgStr)

    print 'finish!'
